/**
 * Author：LSP
 * Date：2020-11-26
 */

// 文件
const files = FileManager.local()

// 弹窗
let message = '脚本下载器'
let options = ['取消', "确定"]
const ensure_index = 1
let textInputHint = '填入脚本地址'
let response = await generateAlert(message, options, true, textInputHint)

if (ensure_index == response.selectIndex) {
    const js_url = response.textFieldValue
    const req = new Request(js_url)
    const codeString = await req.loadString()
    files.writeString(module.filename, codeString)
    // 通知
    const n = new Notification()
    n.title = "下载更新成功"
    n.body = "请点击左上角Done完成，重新进入脚本即可~"
    n.schedule()
}
// 完成
Script.complete()


/**
 * 弹窗
 * @param {信息}} message 
 * @param {选项} options 
 * @param {输入框} textInput 
 * @param {输入框提示} textInputHint 
 */
async function generateAlert(message, options, textInput = false, textInputHint) {
    const alert = new Alert()
    alert.message = message

    if (textInput) {
        alert.addTextField(`${textInputHint}`, '')
    }

    for (const option of options) {
        alert.addAction(option)
    }

    let select_index = await alert.presentAlert()
    let text_input = alert.textFieldValue()

    return {
        selectIndex: select_index,
        textFieldValue: text_input
    }
}